﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Workflow.ComponentModel.Design;
using System.Drawing;
using System.Windows.Forms.Design;
using System.Workflow.ComponentModel;
using System.ComponentModel.Design;

namespace OpenComposite.Workflow
{
	class HorizontalView : DesignerView
	{
		public HorizontalView(int viewId, string text, Image image)
			: base(viewId, text, image)
		{

		}

		public HorizontalView(int viewId, string text, Image image, SequentialActivityDesigner parentDesigner)
			: base(viewId, text, image, parentDesigner)
		{
			_parentDesigner = parentDesigner;
		}

		public HorizontalView(int viewId, string text, Image image, SequentialActivityDesigner parentDesigner, Type associatedDesigner)
			: base(viewId, text, image, parentDesigner)
		{
			_parentDesigner = parentDesigner;
			_associatedDesignerType = associatedDesigner;
		}
		private CompositeActivityDesigner _parentDesigner = null;
		private Type _associatedDesignerType = null;

		public override ActivityDesigner AssociatedDesigner
		{
			get
			{
				return _parentDesigner as ActivityDesigner;
			}
		}

		public override void OnActivate()
		{
			Type type = _associatedDesignerType as Type;
			CompositeActivity activity = this._parentDesigner.Activity as CompositeActivity;
			if ( ( ( type != null ) && ( activity != null ) ) && this._parentDesigner.IsEditable ) {
				if ( !( _parentDesigner is HorizontalCancellationHandlerDesigner ) &&
					 !( _parentDesigner is HorizontalFaultHandlersDesigner ) ) {
					Activity activity2 = WorkflowHelpers.GetAlternateFlowActivity(activity.Activities, _associatedDesignerType);
					if ( activity2 == null ) {
						activity2 = Activator.CreateInstance(type) as Activity;
						try {
							CompositeActivityDesigner.InsertActivities(this._parentDesigner, new HitTestInfo(this._parentDesigner, HitTestLocations.Designer), new List<Activity>(new Activity[] { activity2 }).AsReadOnly(), "AddingImplicitActivity");
						} catch ( Exception exception ) {
							if ( exception != CheckoutException.Canceled ) {
								IUIService service = this._parentDesigner.Activity.Site.GetService(typeof(IUIService)) as IUIService;
								if ( service != null ) {
									service.ShowError(exception.Message);
								}
							}
						}
					}
					_parentDesigner = getDesigner(activity2);
					
				}
			}
			base.OnActivate();
		}

		private CompositeActivityDesigner getDesigner(Activity activity)
		{
			CompositeActivityDesigner designer = null;
			if ( ( activity != null ) && ( activity.Site != null ) ) {
				IDesignerHost service = activity.Site.GetService(typeof(IDesignerHost)) as IDesignerHost;
				if ( service != null ) {
					designer = service.GetDesigner(activity) as CompositeActivityDesigner;
				}
			}
			return designer;
		}

	}
}
